#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
主播招募智能体工作台 - 多用户会话隔离优化版
Multi-User Streamer Recruitment Workbench - Session Isolation Optimized

优化内容：
1. 实现真正的多用户会话隔离
2. 增强用户标识管理（userKey）
3. 会话健康监控和验证
4. 数据一致性检查
5. 优化的错误处理和调试
6. 修复Unicode编码错误

作者: AI Assistant
版本: 2.0.1 (编码修复版)
"""

import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox
import requests
import json
import threading
import time
from datetime import datetime
from urllib.parse import urljoin
import uuid
import sys
import traceback
import hashlib
import locale

class StreamerRecruitmentWorkbench:
    """主播招募智能体工作台主类 - 会话隔离优化版"""
    
    def __init__(self, root):
        self.root = root
        self.root.title("主播招募智能体工作台 v2.0.1 (编码修复版)")
        self.root.geometry("1400x800")
        self.root.configure(bg='#f0f0f0')
        
        # 设置最小窗口大小
        self.root.minsize(1200, 600)
        
        # 编码配置优化
        self.setup_encoding()
        
        # n8n服务器配置
        self.n8n_base_url = "http://localhost:5678"
        self.webhook_endpoint = "/webhook/chat"
        
        # 创建HTTP会话，确保编码安全
        self.session = requests.Session()
        self.session.headers.update({
            'User-Agent': 'StreamerWorkbench/2.0.1',
            'Accept-Charset': 'utf-8'
        })
        
        # 数据存储
        self.users = {}  # 用户数据字典
        self.current_user = None  # 当前选中的用户
        self.auto_refresh = True  # 自动刷新开关
        self.refresh_thread = None  # 刷新线程
        
        # 新增：会话状态监控
        self.session_monitor = {
            'active_sessions': {},      # 活跃会话
            'last_activity': {},        # 最后活动时间
            'session_health': {},       # 会话健康状态
            'user_keys': {}             # 用户唯一标识映射
        }
        
        # 调试模式
        self.debug_mode = True
        
        # 阶段颜色映射
        self.stage_colors = {
            "问候开场": "#FF6B6B",
            "初步筛选": "#4ECDC4", 
            "工作详情": "#45B7D1",
            "照片审核": "#FFA07A",
            "引导照片": "#FFA07A",
            "试镜准备": "#98D8C8",
            "试镜阶段": "#98D8C8",
            "评估中": "#F7DC6F",
            "账号技术": "#BB8FCE",
            "答疑解惑": "#85C1E9",
            "话题引导": "#BDC3C7",
            "已完成": "#82E0AA",
            "未知": "#95A5A6"
        }
        
        # 初始化界面
        self.setup_ui()
        
        # 启动自动刷新
        self.start_auto_refresh()
        
        # 添加示例用户（可选）
        self.add_sample_users()
        
        # 测试连接
        self.test_n8n_connection()
    
    def setup_encoding(self):
        """设置编码配置"""
        try:
            # 确保控制台输出支持UTF-8
            if hasattr(sys.stdout, 'reconfigure'):
                sys.stdout.reconfigure(encoding='utf-8')
            
            # 设置默认语言环境
            try:
                locale.setlocale(locale.LC_ALL, '')
            except:
                pass
                
        except Exception as e:
            print(f"编码设置警告: {e}")
        
    def generate_user_key(self, username, session_id=None):
        """生成稳定的用户标识符"""
        if not session_id:
            # 基于用户名和时间戳生成唯一标识
            timestamp = str(int(time.time()))[-6:]  # 取时间戳后6位
            session_id = f"session_{username}_{timestamp}"
        
        # 从session_id中提取唯一标识
        if '_' in session_id:
            suffix = session_id.split('_')[-1]
        else:
            # 如果session_id格式不标准，使用哈希
            suffix = hashlib.md5(session_id.encode()).hexdigest()[:8]
        
        user_key = f"{username}_{suffix}"
        return user_key, session_id
    
    def test_n8n_connection(self):
        """启动时测试n8n连接"""
        def test_connection():
            try:
                response = self.session.get(f"{self.n8n_base_url}/healthz", timeout=5)
                if response.status_code == 200:
                    self.update_status("n8n连接正常", "#2ecc71")
                    self.log_debug("✅ n8n服务器连接测试成功")
                else:
                    self.update_status("n8n连接异常", "#e74c3c")
                    self.log_debug(f"⚠️ n8n服务器响应异常: {response.status_code}")
            except requests.exceptions.ConnectionError:
                self.update_status("n8n连接失败", "#e74c3c")
                self.log_debug(f"❌ 无法连接到n8n服务器: {self.n8n_base_url}")
            except Exception as e:
                self.update_status("连接测试失败", "#e74c3c")
                self.log_debug(f"❌ 连接测试异常: {str(e)}")
        
        threading.Thread(target=test_connection, daemon=True).start()
    
    def log_debug(self, message):
        """调试日志输出 - 支持中文"""
        if self.debug_mode:
            timestamp = datetime.now().strftime("%H:%M:%S")
            try:
                print(f"[{timestamp}] {message}")
            except UnicodeEncodeError:
                # 如果输出中文失败，使用ASCII安全模式
                safe_message = message.encode('ascii', 'ignore').decode('ascii')
                print(f"[{timestamp}] {safe_message}")
        
    def setup_ui(self):
        """设置用户界面"""
        try:
            # 主框架
            main_frame = tk.Frame(self.root, bg='#f0f0f0')
            main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
            
            # 顶部控制栏
            self.setup_control_bar(main_frame)
            
            # 主内容区域
            content_frame = tk.Frame(main_frame, bg='#f0f0f0')
            content_frame.pack(fill=tk.BOTH, expand=True, pady=(10, 0))
            
            # 左侧用户列表
            self.setup_user_list(content_frame)
            
            # 右侧聊天区域
            self.setup_chat_area(content_frame)
            
            print("✅ 界面初始化完成")
            
        except Exception as e:
            self.show_error("界面初始化失败", str(e))
            
    def setup_control_bar(self, parent):
        """设置顶部控制栏"""
        control_frame = tk.Frame(parent, bg='#2c3e50', height=60)
        control_frame.pack(fill=tk.X)
        control_frame.pack_propagate(False)
        
        # 标题
        title_label = tk.Label(
            control_frame, 
            text="📱 主播招募智能体工作台 v2.0.1 (编码修复版)", 
            font=("Arial", 16, "bold"),
            fg='white', 
            bg='#2c3e50'
        )
        title_label.pack(side=tk.LEFT, padx=20, pady=15)
        
        # 状态显示
        self.status_label = tk.Label(
            control_frame,
            text="🟡 系统启动中...",
            font=("Arial", 10),
            fg='#f39c12',
            bg='#2c3e50'
        )
        self.status_label.pack(side=tk.LEFT, padx=(0, 20), pady=15)
        
        # 控制按钮
        button_frame = tk.Frame(control_frame, bg='#2c3e50')
        button_frame.pack(side=tk.RIGHT, padx=20, pady=10)
        
        # 控制按钮（保持原有功能）
        buttons = [
            ("🔗 测试连接", self.manual_test_connection, '#9b59b6'),
            ("🔄 刷新", self.manual_refresh, '#3498db'),
            ("🗑️ 清除所有", self.clear_all_data, '#e74c3c'),
            ("⚙️ 设置", self.open_settings, '#95a5a6')
        ]
        
        for text, command, color in buttons:
            btn = tk.Button(
                button_frame,
                text=text,
                command=command,
                bg=color,
                fg='white',
                font=("Arial", 10),
                padx=15,
                pady=5,
                border=0,
                cursor="hand2"
            )
            btn.pack(side=tk.LEFT, padx=5)
        
        # 开关控制
        self.auto_refresh_var = tk.BooleanVar(value=True)
        auto_refresh_check = tk.Checkbutton(
            button_frame,
            text="自动刷新",
            variable=self.auto_refresh_var,
            command=self.toggle_auto_refresh,
            fg='white',
            bg='#2c3e50',
            selectcolor='#2c3e50',
            font=("Arial", 10),
            cursor="hand2"
        )
        auto_refresh_check.pack(side=tk.LEFT, padx=10)
        
        self.debug_var = tk.BooleanVar(value=True)
        debug_check = tk.Checkbutton(
            button_frame,
            text="调试模式",
            variable=self.debug_var,
            command=self.toggle_debug,
            fg='white',
            bg='#2c3e50',
            selectcolor='#2c3e50',
            font=("Arial", 10),
            cursor="hand2"
        )
        debug_check.pack(side=tk.LEFT, padx=5)
    
    def toggle_debug(self):
        """切换调试模式"""
        self.debug_mode = self.debug_var.get()
        if self.debug_mode:
            self.log_debug("🔍 调试模式已启用")
        else:
            print("🔇 调试模式已禁用")
    
    def manual_test_connection(self):
        """手动测试连接"""
        self.update_status("测试连接中...", "#f39c12")
        
        def test_connection():
            try:
                self.log_debug(f"🔗 测试连接到: {self.n8n_base_url}")
                response = self.session.get(f"{self.n8n_base_url}/healthz", timeout=10)
                
                if response.status_code == 200:
                    self.update_status("连接成功", "#2ecc71")
                    self.root.after(0, lambda: messagebox.showinfo("连接测试", "✅ n8n服务器连接成功！"))
                    self.log_debug("✅ n8n连接测试成功")
                else:
                    self.update_status(f"连接异常({response.status_code})", "#e74c3c")
                    self.root.after(0, lambda: messagebox.showwarning("连接测试", f"❌ 服务器响应异常\n状态码: {response.status_code}"))
                    self.log_debug(f"⚠️ n8n响应异常: {response.status_code}")
                    
            except requests.exceptions.ConnectionError:
                self.update_status("连接失败", "#e74c3c")
                self.root.after(0, lambda: messagebox.showerror("连接测试", f"❌ 无法连接到n8n服务器\n\n地址: {self.n8n_base_url}\n\n请检查:\n1. n8n服务是否运行\n2. 地址是否正确\n3. 防火墙设置"))
                self.log_debug(f"❌ 连接失败: {self.n8n_base_url}")
                
            except requests.exceptions.Timeout:
                self.update_status("连接超时", "#e74c3c")
                self.root.after(0, lambda: messagebox.showerror("连接测试", "❌ 连接超时\n\n请检查网络连接"))
                self.log_debug("⏱️ 连接超时")
                
            except Exception as e:
                self.update_status("测试失败", "#e74c3c")
                self.root.after(0, lambda: messagebox.showerror("连接测试", f"❌ 连接测试失败\n\n错误: {str(e)}"))
                self.log_debug(f"❌ 连接测试异常: {str(e)}")
        
        threading.Thread(target=test_connection, daemon=True).start()
        
    def setup_user_list(self, parent):
        """设置左侧用户列表"""
        # 用户列表框架
        user_frame = tk.Frame(parent, bg='white', relief=tk.RAISED, bd=1)
        user_frame.pack(side=tk.LEFT, fill=tk.Y, padx=(0, 10))
        user_frame.config(width=380)  # 增加宽度以显示更多信息
        user_frame.pack_propagate(False)
        
        # 用户列表标题
        user_title_frame = tk.Frame(user_frame, bg='#34495e', height=40)
        user_title_frame.pack(fill=tk.X)
        user_title_frame.pack_propagate(False)
        
        user_title = tk.Label(
            user_title_frame,
            text="👥 用户列表 (会话隔离)",
            font=("Arial", 12, "bold"),
            fg='white',
            bg='#34495e'
        )
        user_title.pack(pady=10)
        
        # 用户统计信息
        self.user_stats_label = tk.Label(
            user_frame,
            text="总用户: 0 | 活跃: 0 | 健康会话: 0",
            font=("Arial", 9),
            fg='#7f8c8d',
            bg='white',
            pady=5
        )
        self.user_stats_label.pack(fill=tk.X)
        
        # 用户列表容器
        user_list_frame = tk.Frame(user_frame, bg='white')
        user_list_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=(0, 10))
        
        # 滚动条
        user_scrollbar = ttk.Scrollbar(user_list_frame)
        user_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 用户列表
        self.user_listbox = tk.Listbox(
            user_list_frame,
            yscrollcommand=user_scrollbar.set,
            font=("Arial", 10),
            selectmode=tk.SINGLE,
            bg='#f8f9fa',
            selectbackground='#3498db',
            selectforeground='white',
            height=15,
            activestyle='none'
        )
        self.user_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        self.user_listbox.bind('<<ListboxSelect>>', self.on_user_select)
        self.user_listbox.bind('<Double-Button-1>', self.on_user_double_click)
        
        user_scrollbar.config(command=self.user_listbox.yview)
        
        # 用户操作按钮
        user_button_frame = tk.Frame(user_frame, bg='white')
        user_button_frame.pack(fill=tk.X, padx=10, pady=(0, 10))
        
        # 添加用户按钮
        add_user_btn = tk.Button(
            user_button_frame,
            text="➕ 添加新用户",
            command=self.add_new_user,
            bg='#27ae60',
            fg='white',
            font=("Arial", 10),
            pady=8,
            border=0,
            cursor="hand2"
        )
        add_user_btn.pack(fill=tk.X, pady=(0, 5))
        
        # 删除用户按钮
        delete_user_btn = tk.Button(
            user_button_frame,
            text="🗑️ 删除选中用户",
            command=self.delete_selected_user,
            bg='#e74c3c',
            fg='white',
            font=("Arial", 10),
            pady=8,
            border=0,
            cursor="hand2"
        )
        delete_user_btn.pack(fill=tk.X)
        
    def setup_chat_area(self, parent):
        """设置右侧聊天区域"""
        # 聊天区域框架
        chat_frame = tk.Frame(parent, bg='white', relief=tk.RAISED, bd=1)
        chat_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
        
        # 聊天标题栏
        chat_title_frame = tk.Frame(chat_frame, bg='#34495e', height=50)
        chat_title_frame.pack(fill=tk.X)
        chat_title_frame.pack_propagate(False)
        
        self.chat_title_label = tk.Label(
            chat_title_frame,
            text="请选择用户开始对话",
            font=("Arial", 12, "bold"),
            fg='white',
            bg='#34495e'
        )
        self.chat_title_label.pack(pady=15)
        
        # 聊天历史区域
        chat_history_frame = tk.Frame(chat_frame, bg='white')
        chat_history_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        self.chat_display = scrolledtext.ScrolledText(
            chat_history_frame,
            wrap=tk.WORD,
            font=("Arial", 11),
            bg='#f8f9fa',
            state=tk.DISABLED,
            padx=10,
            pady=10
        )
        self.chat_display.pack(fill=tk.BOTH, expand=True)
        
        # 配置文本标签样式
        self.chat_display.tag_config('user', foreground='#2c3e50', font=("Arial", 11, "bold"))
        self.chat_display.tag_config('ai', foreground='#27ae60', font=("Arial", 11))
        self.chat_display.tag_config('system', foreground='#e74c3c', font=("Arial", 10, "italic"))
        self.chat_display.tag_config('timestamp', foreground='#7f8c8d', font=("Arial", 9))
        self.chat_display.tag_config('debug', foreground='#9b59b6', font=("Arial", 9, "italic"))
        self.chat_display.tag_config('warning', foreground='#f39c12', font=("Arial", 10, "bold"))
        
        # 输入区域
        input_frame = tk.Frame(chat_frame, bg='white')
        input_frame.pack(fill=tk.X, padx=10, pady=(0, 10))
        
        # 输入标签
        input_label = tk.Label(
            input_frame,
            text="💬 发送消息 (Ctrl+Enter快速发送):",
            font=("Arial", 10),
            bg='white'
        )
        input_label.pack(anchor=tk.W, pady=(0, 5))
        
        # 输入框和按钮的容器
        input_container = tk.Frame(input_frame, bg='white')
        input_container.pack(fill=tk.X)
        
        self.message_entry = tk.Text(
            input_container,
            height=3,
            font=("Arial", 11),
            wrap=tk.WORD,
            bg='white',
            relief=tk.SOLID,
            bd=1
        )
        self.message_entry.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0, 10))
        self.message_entry.bind('<Control-Return>', self.send_message_event)
        self.message_entry.bind('<KeyPress>', self.on_typing)
        
        send_btn = tk.Button(
            input_container,
            text="📤\n发送",
            command=self.send_message,
            bg='#3498db',
            fg='white',
            font=("Arial", 10, "bold"),
            width=8,
            height=3,
            border=0,
            cursor="hand2"
        )
        send_btn.pack(side=tk.RIGHT)
        
        # 快捷操作按钮
        shortcut_frame = tk.Frame(input_frame, bg='white')
        shortcut_frame.pack(fill=tk.X, pady=(5, 0))
        
        shortcuts = [
            ("👋 问候", "你好"),
            ("📊 查看状态", "当前是什么阶段？"),
            ("💰 工资咨询", "工资怎么样？"),
            ("📷 发照片", "我发照片给你看看"),
            ("🎬 试镜", "试镜需要准备什么？"),
            ("🧪 测试连接", "TEST_CONNECTION"),
            ("🗑️ 清除记录", "CLEAR_HISTORY")
        ]
        
        for text, command in shortcuts:
            btn = tk.Button(
                shortcut_frame,
                text=text,
                command=lambda cmd=command: self.insert_shortcut(cmd),
                bg='#ecf0f1',
                font=("Arial", 9),
                padx=8,
                pady=2,
                border=0,
                cursor="hand2"
            )
            btn.pack(side=tk.LEFT, padx=2)
    
    def add_sample_users(self):
        """添加示例用户"""
        sample_users = ["张小美", "李主播", "王新人"]
        for username in sample_users:
            if username not in self.users:
                session_id = str(uuid.uuid4())
                user_key, session_id = self.generate_user_key(username, session_id)
                
                self.users[username] = {
                    'messages': [],
                    'stage': '未知',
                    'last_active': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    'session_id': session_id,
                    'user_key': user_key
                }
                
                # 更新会话监控
                self.session_monitor['active_sessions'][username] = session_id
                self.session_monitor['user_keys'][username] = user_key
                self.session_monitor['session_health'][username] = 'healthy'
                
        self.update_user_list()
    
    def insert_shortcut(self, text):
        """插入快捷文本"""
        if text == "CLEAR_HISTORY":
            if self.current_user:
                if messagebox.askyesno("确认", f"确定要清除用户 {self.current_user} 的聊天记录吗？"):
                    self.clear_user_history(self.current_user)
        elif text == "TEST_CONNECTION":
            self.manual_test_connection()
        else:
            self.message_entry.delete(1.0, tk.END)
            self.message_entry.insert(1.0, text)
            self.message_entry.focus()
    
    def add_new_user(self):
        """添加新用户"""
        dialog = tk.Toplevel(self.root)
        dialog.title("添加新用户")
        dialog.geometry("400x200")
        dialog.transient(self.root)
        dialog.grab_set()
        dialog.resizable(False, False)
        
        # 居中显示
        dialog.update_idletasks()
        x = (dialog.winfo_screenwidth() // 2) - (400 // 2)
        y = (dialog.winfo_screenheight() // 2) - (200 // 2)
        dialog.geometry(f"400x200+{x}+{y}")
        
        main_frame = tk.Frame(dialog, bg='white', padx=20, pady=20)
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        tk.Label(
            main_frame, 
            text="👤 请输入新用户名", 
            font=("Arial", 12, "bold"),
            bg='white'
        ).pack(pady=(0, 15))
        
        username_entry = tk.Entry(
            main_frame, 
            font=("Arial", 11), 
            width=25,
            relief=tk.SOLID,
            bd=1
        )
        username_entry.pack(pady=5)
        username_entry.focus()
        
        tk.Label(
            main_frame,
            text="用户名将用于区分不同的对话会话（支持会话隔离）",
            font=("Arial", 9),
            fg='#7f8c8d',
            bg='white'
        ).pack(pady=(5, 15))
        
        def confirm_add():
            username = username_entry.get().strip()
            if username:
                if username not in self.users:
                    # 生成新的会话标识
                    session_id = str(uuid.uuid4())
                    user_key, session_id = self.generate_user_key(username, session_id)
                    
                    self.users[username] = {
                        'messages': [],
                        'stage': '未知',
                        'last_active': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                        'session_id': session_id,
                        'user_key': user_key
                    }
                    
                    # 更新会话监控
                    self.session_monitor['active_sessions'][username] = session_id
                    self.session_monitor['user_keys'][username] = user_key
                    self.session_monitor['session_health'][username] = 'healthy'
                    self.session_monitor['last_activity'][username] = datetime.now()
                    
                    self.update_user_list()
                    dialog.destroy()
                    messagebox.showinfo("成功", f"用户 {username} 已添加\n会话ID: {user_key}")
                    self.select_user(username)
                else:
                    messagebox.showwarning("警告", "用户已存在")
                    username_entry.focus()
            else:
                messagebox.showwarning("警告", "请输入用户名")
                username_entry.focus()
        
        button_frame = tk.Frame(main_frame, bg='white')
        button_frame.pack(pady=20)
        
        tk.Button(
            button_frame, 
            text="✅ 确定", 
            command=confirm_add,
            bg='#3498db',
            fg='white',
            font=("Arial", 10),
            padx=20,
            pady=5,
            border=0,
            cursor="hand2"
        ).pack(side=tk.LEFT, padx=5)
        
        tk.Button(
            button_frame,
            text="❌ 取消",
            command=dialog.destroy,
            bg='#95a5a6',
            fg='white',
            font=("Arial", 10),
            padx=20,
            pady=5,
            border=0,
            cursor="hand2"
        ).pack(side=tk.LEFT, padx=5)
        
        username_entry.bind('<Return>', lambda e: confirm_add())
    
    def delete_selected_user(self):
        """删除选中的用户"""
        if not self.current_user:
            messagebox.showwarning("警告", "请先选择要删除的用户")
            return
            
        if messagebox.askyesno("确认删除", f"确定要删除用户 '{self.current_user}' 及其所有聊天记录吗？\n\n此操作无法撤销！"):
            if self.current_user in self.users:
                # 清理会话监控数据
                if self.current_user in self.session_monitor['active_sessions']:
                    del self.session_monitor['active_sessions'][self.current_user]
                if self.current_user in self.session_monitor['user_keys']:
                    del self.session_monitor['user_keys'][self.current_user]
                if self.current_user in self.session_monitor['session_health']:
                    del self.session_monitor['session_health'][self.current_user]
                if self.current_user in self.session_monitor['last_activity']:
                    del self.session_monitor['last_activity'][self.current_user]
                
                del self.users[self.current_user]
                self.current_user = None
                self.update_user_list()
                self.update_chat_display()
                messagebox.showinfo("删除成功", "用户已删除")
    
    def select_user(self, username):
        """选中指定用户"""
        for i in range(self.user_listbox.size()):
            item_text = self.user_listbox.get(i)
            if item_text.startswith(username + " - "):
                self.user_listbox.selection_clear(0, tk.END)
                self.user_listbox.selection_set(i)
                self.user_listbox.see(i)
                self.current_user = username
                self.update_chat_display()
                break
    
    def on_user_select(self, event):
        """用户选择事件"""
        selection = self.user_listbox.curselection()
        if selection:
            item_text = self.user_listbox.get(selection[0])
            username = item_text.split(' - ')[0]
            self.current_user = username
            self.update_chat_display()
    
    def on_user_double_click(self, event):
        """用户双击事件"""
        if self.current_user:
            self.message_entry.focus()
    
    def on_typing(self, event):
        """用户输入事件"""
        pass
    
    def update_user_list(self):
        """更新用户列表"""
        self.user_listbox.delete(0, tk.END)
        
        total_users = len(self.users)
        active_users = 0
        healthy_sessions = 0
        
        for username, user_data in self.users.items():
            stage = user_data.get('stage', '未知')
            message_count = len(user_data.get('messages', []))
            last_active = user_data.get('last_active', 'N/A')
            user_key = user_data.get('user_key', 'N/A')
            
            # 获取会话健康状态
            session_health = self.session_monitor['session_health'].get(username, 'unknown')
            if session_health in ['healthy', 'success']:
                healthy_sessions += 1
                health_icon = '🟢'
            elif session_health == 'error':
                health_icon = '🔴'
            else:
                health_icon = '⚪'
            
            # 判断活跃状态
            try:
                last_time = datetime.strptime(last_active, "%Y-%m-%d %H:%M:%S")
                if (datetime.now() - last_time).total_seconds() < 3600:
                    active_users += 1
                    status_icon = "🟢"
                else:
                    status_icon = "⚪"
            except:
                status_icon = "❓"
            
            # 显示用户标识的前6位
            user_key_short = user_key.split('_')[-1][:6] if '_' in user_key else user_key[:6]
            
            display_text = f"{username} - {stage} ({message_count}条) {health_icon}{status_icon} [{user_key_short}]"
            self.user_listbox.insert(tk.END, display_text)
            
            # 设置颜色
            index = self.user_listbox.size() - 1
            color = self.stage_colors.get(stage, self.stage_colors['未知'])
            
            # 根据会话健康状态调整颜色
            if session_health == 'error':
                color = '#ff6b6b'
            
            self.user_listbox.itemconfig(index, bg=color, selectbackground='#2c3e50')
        
        # 更新统计信息
        self.user_stats_label.config(text=f"总用户: {total_users} | 活跃: {active_users} | 健康会话: {healthy_sessions}")
    
    def update_chat_display(self):
        """更新聊天显示"""
        if not self.current_user:
            self.chat_title_label.config(text="请选择用户开始对话")
            self.chat_display.config(state=tk.NORMAL)
            self.chat_display.delete(1.0, tk.END)
            self.chat_display.insert(tk.END, "👋 欢迎使用主播招募智能体工作台 v2.0.1\n\n")
            self.chat_display.insert(tk.END, "🔧 新版本特性：\n")
            self.chat_display.insert(tk.END, "• ✅ 真正的多用户会话隔离\n")
            self.chat_display.insert(tk.END, "• ✅ 用户唯一标识管理（userKey）\n")
            self.chat_display.insert(tk.END, "• ✅ 会话健康状态监控\n")
            self.chat_display.insert(tk.END, "• ✅ 数据一致性验证\n")
            self.chat_display.insert(tk.END, "• ✅ 增强的错误处理和调试\n")
            self.chat_display.insert(tk.END, "• ✅ 修复Unicode编码错误\n\n")
            self.chat_display.insert(tk.END, "请从左侧用户列表中选择一个用户开始对话，或点击'添加新用户'创建新的会话。\n\n")
            self.chat_display.config(state=tk.DISABLED)
            return
            
        user_data = self.users.get(self.current_user, {})
        messages = user_data.get('messages', [])
        stage = user_data.get('stage', '未知')
        session_id = user_data.get('session_id', 'N/A')
        user_key = user_data.get('user_key', 'N/A')
        
        # 获取会话诊断信息
        session_health = self.session_monitor['session_health'].get(self.current_user, 'unknown')
        last_activity = self.session_monitor['last_activity'].get(self.current_user, 'N/A')
        
        # 更新标题
        health_icon = '🟢' if session_health in ['healthy', 'success'] else '🔴' if session_health == 'error' else '⚪'
        self.chat_title_label.config(
            text=f"💬 与 {self.current_user} 的对话 - {stage} {health_icon}"
        )
        
        # 清空并重新填充聊天内容
        self.chat_display.config(state=tk.NORMAL)
        self.chat_display.delete(1.0, tk.END)
        
        # 显示增强的会话信息
        self.chat_display.insert(tk.END, f"📋 会话诊断信息（v2.0.1）\n", 'system')
        self.chat_display.insert(tk.END, f"用户: {self.current_user}\n", 'system')
        self.chat_display.insert(tk.END, f"阶段: {stage}\n", 'system')
        self.chat_display.insert(tk.END, f"会话ID: {session_id[:12]}...\n", 'system')
        self.chat_display.insert(tk.END, f"用户标识: {user_key}\n", 'system')
        self.chat_display.insert(tk.END, f"会话健康: {session_health} {health_icon}\n", 'system')
        self.chat_display.insert(tk.END, f"最后活动: {last_activity}\n", 'system')
        self.chat_display.insert(tk.END, f"消息数量: {len(messages)}\n", 'system')
        self.chat_display.insert(tk.END, f"n8n地址: {self.n8n_base_url}\n", 'debug')
        self.chat_display.insert(tk.END, "\n" + "="*50 + "\n\n", 'system')
        
        # 显示消息历史
        if not messages:
            self.chat_display.insert(tk.END, "🔰 这是一个新的对话，发送消息开始招募流程吧！\n\n", 'system')
            self.chat_display.insert(tk.END, "💡 v2.0.1特性: 每个用户的对话完全独立，支持真正的多用户并发\n\n", 'system')
        else:
            for message in messages:
                timestamp = message.get('timestamp', '')
                sender = message.get('sender', '')
                content = message.get('content', '')
                
                if sender == 'user':
                    self.chat_display.insert(tk.END, f"[{timestamp}] ", 'timestamp')
                    self.chat_display.insert(tk.END, f"👤 {self.current_user}:\n", 'user')
                    self.chat_display.insert(tk.END, f"{content}\n\n", 'user')
                else:
                    self.chat_display.insert(tk.END, f"[{timestamp}] ", 'timestamp')
                    self.chat_display.insert(tk.END, f"🤖 TT老师:\n", 'ai')
                    self.chat_display.insert(tk.END, f"{content}\n\n", 'ai')
        
        self.chat_display.config(state=tk.DISABLED)
        self.chat_display.see(tk.END)
    
    def send_message_event(self, event):
        """发送消息事件（Ctrl+Enter）"""
        self.send_message()
        return 'break'
    
    def send_message(self):
        """发送消息到AI"""
        if not self.current_user:
            messagebox.showwarning("警告", "请先选择用户")
            return
            
        message = self.message_entry.get(1.0, tk.END).strip()
        if not message:
            return
        
        # 清空输入框
        self.message_entry.delete(1.0, tk.END)
        
        # 添加用户消息到历史
        timestamp = datetime.now().strftime("%H:%M:%S")
        self.add_message_to_history(self.current_user, 'user', message, timestamp)
        
        # 更新状态
        self.update_status("发送中...", "#f39c12")
        
        # 发送到n8n并获取AI回复
        threading.Thread(target=self.send_to_n8n, args=(message,), daemon=True).start()
    
    def validate_payload(self, payload):
        """验证发送数据的完整性"""
        required_fields = ['chatInput', 'username', 'sessionId', 'userKey']
        for field in required_fields:
            if not payload.get(field):
                self.log_debug(f"❌ 缺少必要字段: {field}")
                return False
        
        # 验证用户名一致性
        if payload['username'] != self.current_user:
            self.log_debug(f"❌ 用户名不匹配: {payload['username']} != {self.current_user}")
            return False
        
        return True
    
    def validate_response(self, response, expected_user):
        """验证响应数据的正确性"""
        response_user = response.get('username', '')
        if response_user and response_user != expected_user:
            self.log_debug(f"⚠️ 响应用户不匹配: 期望{expected_user}, 收到{response_user}")
            return False
        
        if response.get('error'):
            self.log_debug(f"❌ 响应包含错误: {response.get('error')}")
            return False
        
        return True
    
    def check_session_health(self, username, session_id):
        """检查会话健康状态"""
        if username not in self.session_monitor['active_sessions']:
            self.session_monitor['active_sessions'][username] = session_id
            self.session_monitor['session_health'][username] = 'healthy'
        else:
            if self.session_monitor['active_sessions'][username] != session_id:
                self.log_debug(f"🔄 用户{username}的session_id已更新")
                self.session_monitor['active_sessions'][username] = session_id
        
        self.session_monitor['last_activity'][username] = datetime.now()
    
    def update_session_monitor(self, username, user_key, status):
        """更新会话监控状态"""
        self.session_monitor['session_health'][username] = status
        self.session_monitor['last_activity'][username] = datetime.now()
        if user_key:
            self.session_monitor['user_keys'][username] = user_key
        
        # 在UI线程中更新显示
        self.root.after(0, self.update_user_list)
    
    def send_to_n8n(self, message):
        """发送消息到n8n工作流 - 会话隔离优化版（修复编码错误）"""
        try:
            user_data = self.users.get(self.current_user, {})
            session_id = user_data.get('session_id', str(uuid.uuid4()))
            user_key = user_data.get('user_key')
            
            # 如果没有user_key，生成一个
            if not user_key:
                user_key, session_id = self.generate_user_key(self.current_user, session_id)
                user_data['user_key'] = user_key
                user_data['session_id'] = session_id
            
            # 会话健康检查
            self.check_session_health(self.current_user, session_id)
            
            # 构建优化的数据格式
            payload = {
                "chatInput": message,
                "username": self.current_user,
                "sessionId": session_id,
                "userKey": user_key,
                "timestamp": datetime.now().isoformat(),
                "metadata": {
                    "source": "workbench_v2",
                    "version": "2.0.1",
                    "user_agent": "StreamerWorkbench/2.0.1"
                }
            }
            
            # 验证数据完整性
            if not self.validate_payload(payload):
                self.log_debug("❌ 数据验证失败，停止发送")
                return
            
            url = urljoin(self.n8n_base_url, self.webhook_endpoint)
            
            self.log_debug(f"🚀 发送请求到: {url}")
            self.log_debug(f"👤 当前用户: {self.current_user}")
            self.log_debug(f"🔑 用户标识: {user_key}")
            self.log_debug(f"📦 请求数据: {json.dumps(payload, ensure_ascii=False, indent=2)}")
            
            # 发送请求 - 修复：移除包含中文的HTTP头部，使用session
            response = self.session.post(
                url,
                json=payload,
                timeout=30,
                headers={
                    'Content-Type': 'application/json; charset=utf-8',
                    'Accept': 'application/json'
                    # 移除了包含中文的自定义头部：
                    # 'X-User-Key': user_key,
                    # 'X-Session-Id': session_id, 
                    # 'X-Username': self.current_user
                }
            )
            
            self.log_debug(f"📊 响应状态: {response.status_code}")
            
            if response.status_code == 200:
                result = response.json()
                self.log_debug(f"📨 响应数据: {json.dumps(result, ensure_ascii=False, indent=2)}")
                
                # 验证响应
                if not self.validate_response(result, self.current_user):
                    self.log_debug("⚠️ 响应验证失败，可能存在用户混淆")
                
                # 处理响应
                ai_response = result.get('output', '系统错误，请重试')
                stage = result.get('stage', '未知')
                returned_username = result.get('username', '')
                returned_user_key = result.get('userKey', '')
                
                # 用户身份确认
                if returned_username and returned_username != self.current_user:
                    self.log_debug(f"⚠️ 用户身份不匹配: 期望{self.current_user}, 收到{returned_username}")
                    ai_response = f"[系统提示：检测到用户身份异常，请重新发送] {ai_response}"
                
                # 阶段名称转换
                stage_names = {
                    0: "照片审核", 1: "问候开场", 2: "初步筛选",
                    3: "工作详情", 4: "引导照片", 5: "试镜阶段", 
                    6: "账号技术", 7: "答疑解惑", 8: "话题引导"
                }
                
                if isinstance(stage, (int, str)) and str(stage).isdigit():
                    stage = stage_names.get(int(stage), f"阶段{stage}")
                
                # 添加回复到历史
                timestamp = datetime.now().strftime("%H:%M:%S")
                self.add_message_to_history(self.current_user, 'ai', ai_response, timestamp)
                
                # 更新用户状态
                self.update_user_stage(self.current_user, stage)
                
                # 更新会话监控
                self.update_session_monitor(self.current_user, returned_user_key or user_key, 'success')
                
                self.update_status("就绪", "#2ecc71")
                self.log_debug("✅ 消息发送成功")
                
            else:
                error_msg = f"请求失败，状态码: {response.status_code}\n响应: {response.text[:200]}"
                timestamp = datetime.now().strftime("%H:%M:%S")
                self.add_message_to_history(self.current_user, 'ai', error_msg, timestamp)
                self.update_status("发送失败", "#e74c3c")
                self.update_session_monitor(self.current_user, user_key, 'error')
                
        except UnicodeEncodeError as e:
            error_msg = f"编码错误: 请检查用户名是否包含特殊字符"
            timestamp = datetime.now().strftime("%H:%M:%S")
            self.add_message_to_history(self.current_user, 'ai', error_msg, timestamp)
            self.update_status("编码错误", "#e74c3c")
            self.log_debug(f"❌ Unicode编码错误: {str(e)}")
            self.update_session_monitor(self.current_user, user_key, 'error')
                
        except requests.exceptions.Timeout:
            error_msg = "请求超时，请检查网络连接"
            timestamp = datetime.now().strftime("%H:%M:%S")
            self.add_message_to_history(self.current_user, 'ai', error_msg, timestamp)
            self.update_status("连接超时", "#e74c3c")
            self.update_session_monitor(self.current_user, user_key, 'error')
            
        except requests.exceptions.ConnectionError:
            error_msg = "连接失败，无法连接到n8n服务器"
            timestamp = datetime.now().strftime("%H:%M:%S")
            self.add_message_to_history(self.current_user, 'ai', error_msg, timestamp)
            self.update_status("连接失败", "#e74c3c")
            self.update_session_monitor(self.current_user, user_key, 'error')
            
        except Exception as e:
            error_msg = f"系统异常: {str(e)}"
            timestamp = datetime.now().strftime("%H:%M:%S")
            self.add_message_to_history(self.current_user, 'ai', error_msg, timestamp)
            self.update_status("系统错误", "#e74c3c")
            self.log_debug(f"❌ 系统异常: {traceback.format_exc()}")
            self.update_session_monitor(self.current_user, user_key, 'error')
    
    def add_message_to_history(self, username, sender, content, timestamp):
        """添加消息到历史记录"""
        if username not in self.users:
            session_id = str(uuid.uuid4())
            user_key, session_id = self.generate_user_key(username, session_id)
            
            self.users[username] = {
                'messages': [],
                'stage': '未知',
                'last_active': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                'session_id': session_id,
                'user_key': user_key
            }
        
        message = {
            'timestamp': timestamp,
            'sender': sender,
            'content': content
        }
        
        self.users[username]['messages'].append(message)
        self.users[username]['last_active'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # 在UI线程中更新显示
        self.root.after(0, self.update_display_after_message)
    
    def update_display_after_message(self):
        """消息发送后更新显示"""
        self.update_user_list()
        if self.current_user:
            self.update_chat_display()
    
    def update_user_stage(self, username, stage):
        """更新用户所在阶段"""
        if username in self.users:
            self.users[username]['stage'] = stage
            self.root.after(0, self.update_user_list)
    
    def update_status(self, text, color="#2ecc71"):
        """更新状态显示"""
        status_icons = {
            "就绪": "🟢", "发送中": "🟡", "请求失败": "🔴",
            "连接失败": "🔴", "超时": "🟠", "解析错误": "🔴",
            "系统错误": "🔴", "n8n连接正常": "🟢", "n8n连接异常": "🔴",
            "n8n连接失败": "🔴", "连接成功": "🟢", "连接异常": "🔴",
            "连接超时": "🟠", "测试失败": "🔴", "测试连接中": "🟡",
            "发送失败": "🔴", "系统启动中": "🟡", "编码错误": "🔴"
        }
        
        icon = status_icons.get(text, "🔵")
        self.status_label.config(text=f"{icon} {text}", fg=color)
    
    def clear_user_history(self, username):
        """清除用户聊天记录"""
        if username in self.users:
            # 重新生成会话标识
            new_session_id = str(uuid.uuid4())
            new_user_key, new_session_id = self.generate_user_key(username, new_session_id)
            
            self.users[username]['messages'] = []
            self.users[username]['session_id'] = new_session_id
            self.users[username]['user_key'] = new_user_key
            self.users[username]['stage'] = '未知'
            
            # 更新会话监控
            self.session_monitor['active_sessions'][username] = new_session_id
            self.session_monitor['user_keys'][username] = new_user_key
            self.session_monitor['session_health'][username] = 'healthy'
            
            self.update_display_after_message()
    
    def clear_all_data(self):
        """清除所有数据"""
        if messagebox.askyesno("确认", "确定要清除所有用户数据吗？此操作无法撤销！"):
            self.users = {}
            self.current_user = None
            
            # 清理会话监控数据
            self.session_monitor = {
                'active_sessions': {},
                'last_activity': {},
                'session_health': {},
                'user_keys': {}
            }
            
            self.update_user_list()
            self.update_chat_display()
            messagebox.showinfo("清除完成", "所有用户数据已清除")
    
    def toggle_auto_refresh(self):
        """切换自动刷新"""
        self.auto_refresh = self.auto_refresh_var.get()
        if self.auto_refresh:
            self.log_debug("✅ 自动刷新已启用")
        else:
            self.log_debug("⏸️ 自动刷新已禁用")
    
    def manual_refresh(self):
        """手动刷新"""
        self.update_user_list()
        if self.current_user:
            self.update_chat_display()
        self.log_debug("🔄 手动刷新完成")
    
    def open_settings(self):
        """打开设置对话框"""
        dialog = tk.Toplevel(self.root)
        dialog.title("系统设置")
        dialog.geometry("700x500")
        dialog.transient(self.root)
        dialog.grab_set()
        dialog.resizable(False, False)
        
        # 居中显示
        dialog.update_idletasks()
        x = (dialog.winfo_screenwidth() // 2) - (700 // 2)
        y = (dialog.winfo_screenheight() // 2) - (500 // 2)
        dialog.geometry(f"700x500+{x}+{y}")
        
        main_frame = tk.Frame(dialog, bg='white', padx=20, pady=20)
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        tk.Label(
            main_frame,
            text="⚙️ 系统设置 v2.0.1",
            font=("Arial", 14, "bold"),
            bg='white'
        ).pack(pady=(0, 20))
        
        # n8n服务器地址设置
        tk.Label(
            main_frame,
            text="n8n服务器地址:",
            font=("Arial", 11),
            bg='white'
        ).pack(anchor=tk.W)
        
        url_entry = tk.Entry(
            main_frame,
            font=("Arial", 11),
            width=70,
            relief=tk.SOLID,
            bd=1
        )
        url_entry.pack(fill=tk.X, pady=(5, 10))
        url_entry.insert(0, self.n8n_base_url)
        
        # Webhook路径设置
        tk.Label(
            main_frame,
            text="Webhook路径:",
            font=("Arial", 11),
            bg='white'
        ).pack(anchor=tk.W)
        
        webhook_entry = tk.Entry(
            main_frame,
            font=("Arial", 11),
            width=70,
            relief=tk.SOLID,
            bd=1
        )
        webhook_entry.pack(fill=tk.X, pady=(5, 15))
        webhook_entry.insert(0, self.webhook_endpoint)
        
        # 测试连接按钮
        def test_connection():
            test_url = url_entry.get().strip()
            if test_url:
                try:
                    response = self.session.get(f"{test_url}/healthz", timeout=5)
                    if response.status_code == 200:
                        messagebox.showinfo("连接测试", "✅ n8n服务器连接成功！")
                    else:
                        messagebox.showwarning("连接测试", f"❌ n8n服务器响应异常\n状态码: {response.status_code}")
                except requests.exceptions.ConnectionError:
                    messagebox.showerror("连接测试", f"❌ 无法连接到n8n服务器\n\n地址: {test_url}\n\n请检查:\n1. n8n服务是否运行\n2. 地址是否正确\n3. 防火墙设置")
                except Exception as e:
                    messagebox.showerror("连接测试", f"❌ 连接测试失败\n\n错误: {str(e)}")
            else:
                messagebox.showwarning("连接测试", "请输入服务器地址")
        
        test_btn_frame = tk.Frame(main_frame, bg='white')
        test_btn_frame.pack(fill=tk.X, pady=(0, 20))
        
        tk.Button(
            test_btn_frame,
            text="🔗 测试n8n连接",
            command=test_connection,
            bg='#3498db',
            fg='white',
            font=("Arial", 10),
            padx=15,
            border=0,
            cursor="hand2"
        ).pack(side=tk.LEFT)
        
        # 诊断信息
        info_frame = tk.LabelFrame(main_frame, text="会话隔离诊断信息", bg='white', font=("Arial", 10))
        info_frame.pack(fill=tk.X, pady=(0, 20))
        
        info_text = scrolledtext.ScrolledText(
            info_frame,
            height=10,
            font=("Consolas", 9),
            bg='#f8f9fa'
        )
        info_text.pack(fill=tk.X, padx=10, pady=10)
        
        # 显示诊断信息
        healthy_sessions = sum(1 for status in self.session_monitor['session_health'].values() if status in ['healthy', 'success'])
        active_sessions = len(self.session_monitor['active_sessions'])
        
        diag_info = f"""当前配置 (v2.0.1):
• n8n地址: {self.n8n_base_url}
• Webhook路径: {self.webhook_endpoint}
• 完整URL: {urljoin(self.n8n_base_url, self.webhook_endpoint)}
• 调试模式: {'开启' if self.debug_mode else '关闭'}

会话隔离状态:
• 总用户数: {len(self.users)}
• 活跃会话: {active_sessions}
• 健康会话: {healthy_sessions}
• 当前选中用户: {self.current_user or '无'}

用户标识映射:
{chr(10).join([f'• {user}: {key}' for user, key in self.session_monitor['user_keys'].items()])}

编码优化 (v2.0.1):
• Unicode编码处理: 已优化
• HTTP头部编码: 已修复，移除中文字段
• 会话数据传递: 使用JSON Body
• 控制台输出: 支持UTF-8

n8n优化配置检查:
• 数据标准化处理节点: 是否使用userKey生成逻辑
• Memory节点配置: sessionKey是否使用userKey
• 智能体系统消息: 是否包含用户上下文信息

故障排除步骤:
1. 确认n8n服务正在运行
2. 检查工作流是否已激活并更新到v2.0配置
3. 确认数据标准化处理节点使用新的JavaScript代码
4. 确认Memory节点sessionKey配置为userKey
5. 查看n8n执行日志确认userKey正确传递

常见问题 (已修复):
• "UnicodeEncodeError" - 已修复HTTP头部编码问题
• "Missing chatInput parameter" - 检查数据格式
• "用户身份不匹配" - 检查userKey生成和传递
• "会话串话" - 确认Memory节点使用userKey隔离
"""
        info_text.insert(tk.END, diag_info)
        info_text.config(state=tk.DISABLED)
        
        def save_settings():
            new_url = url_entry.get().strip()
            new_webhook = webhook_entry.get().strip()
            
            changed = False
            if new_url and new_url != self.n8n_base_url:
                self.n8n_base_url = new_url
                changed = True
            
            if new_webhook and new_webhook != self.webhook_endpoint:
                self.webhook_endpoint = new_webhook
                changed = True
            
            if changed:
                messagebox.showinfo("设置保存", "设置已保存！")
                self.log_debug(f"📝 设置已更新: {self.n8n_base_url}{self.webhook_endpoint}")
            
            dialog.destroy()
        
        button_frame = tk.Frame(main_frame, bg='white')
        button_frame.pack(side=tk.BOTTOM, pady=(20, 0))
        
        tk.Button(
            button_frame,
            text="✅ 保存设置",
            command=save_settings,
            bg='#27ae60',
            fg='white',
            font=("Arial", 10),
            padx=20,
            border=0,
            cursor="hand2"
        ).pack(side=tk.LEFT, padx=5)
        
        tk.Button(
            button_frame,
            text="❌ 取消",
            command=dialog.destroy,
            bg='#95a5a6',
            fg='white',
            font=("Arial", 10),
            padx=20,
            border=0,
            cursor="hand2"
        ).pack(side=tk.LEFT, padx=5)
    
    def start_auto_refresh(self):
        """启动自动刷新"""
        def refresh_loop():
            while True:
                time.sleep(30)
                if self.auto_refresh:
                    try:
                        self.root.after(0, self.manual_refresh)
                    except:
                        break
        
        self.refresh_thread = threading.Thread(target=refresh_loop, daemon=True)
        self.refresh_thread.start()
        self.log_debug("🔄 自动刷新已启动")
    
    def show_error(self, title, message):
        """显示错误对话框"""
        messagebox.showerror(title, message)
        self.log_debug(f"❌ {title}: {message}")

def main():
    """主函数"""
    try:
        root = tk.Tk()
        app = StreamerRecruitmentWorkbench(root)
        
        try:
            root.iconbitmap('icon.ico')
        except:
            pass
        
        def on_closing():
            if messagebox.askokcancel("退出", "确定要退出工作台吗？"):
                print("👋 工作台正在关闭...")
                root.destroy()
        
        root.protocol("WM_DELETE_WINDOW", on_closing)
        
        print("🚀 主播招募智能体工作台启动成功 v2.0.1 (编码修复版)")
        print(f"🌐 n8n服务器地址: {app.n8n_base_url}")
        print(f"🔗 webhook路径: {app.webhook_endpoint}")
        print(f"📡 完整URL: {app.n8n_base_url}{app.webhook_endpoint}")
        print("🔧 v2.0.1新特性:")
        print("   ✅ 真正的多用户会话隔离")
        print("   ✅ 用户唯一标识管理（userKey）")
        print("   ✅ 会话健康状态监控")
        print("   ✅ 数据一致性验证")
        print("   ✅ 增强的错误处理和调试")
        print("   ✅ 修复Unicode编码错误")
        print("="*60)
        
        root.mainloop()
        
    except Exception as e:
        print(f"❌ 启动失败: {str(e)}")
        print(f"详细错误: {traceback.format_exc()}")
        messagebox.showerror("启动错误", f"工作台启动失败:\n{str(e)}")

if __name__ == "__main__":
    main()